package xianchengpool;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @功能
 * @创建时间 2019/12/26
 * 会偷任务，线程执行完任务之后会自动那其他为被执行的任务
 */
public class T11_WorkStealingPool {
    public static void main(String[] args) throws IOException {
        ExecutorService service = Executors.newWorkStealingPool();
        System.out.println(Runtime.getRuntime().availableProcessors());
        service.execute(new R(1000));
        service.execute(new R(2000));
        service.execute(new R(2000));
        service.execute(new R(2000));
        service.execute(new R(2000));
        service.execute(new R(2000));
        service.execute(new R(2000)); // daemon
        service.execute(new R(2000));
        service.execute(new R(2000));
        // 由于产生的是精灵线程（守护线程，后台线程），主线程不阻塞的话，看不到输出
        System.out.println(service);
        System.in.read(); //让主函数阻塞
    }
    static class R implements Runnable{

        int time;

        R(int t){
            this.time = t;
        }
        @Override
        public void run() {
            try{
                TimeUnit.MILLISECONDS.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(time+""+Thread.currentThread().getName());
        }
    }
}
